package com.example.demo.config.shiro;

import com.example.demo.entity.Admin;
import com.example.demo.entity.Person;
import com.example.demo.entity.User;
import com.example.demo.service.AdminService;
import com.example.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author: yucs
 * @Date: 2021/9/1 17:39
 * 用来给shiro加缓存的Realm类，为了尽量不影响之前的代码，新建一个类
 * 最初的实现方案是UserRealm类
 */
public class CustomerRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    AdminService adminService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("=====执行了授权=====");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        Person loginPerson = (Person)subject.getPrincipal();
        /**
         * @yucs 2021/8/31 用addRole的方式授权
         * 只要有用户登录，就授予user的权限（所有用户都有普通权限）
         */
        info.addRole("user");
        //如果登录角色是管理员
        if(loginPerson.getRole()== 1){
            info.addRole("admin");
            System.out.println("给管理员授权了");
        }else if(loginPerson.getRole() == 0) {
            System.out.println("用户已授权");
        }else{
            System.out.println("UserRealm授权出错！");
            System.out.println(loginPerson.getRole());
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)  throws AuthenticationException {
        //普通用户的认证逻辑
        if(authenticationToken instanceof CommonUserToken){
            UsernamePasswordToken inputToken = (UsernamePasswordToken)authenticationToken;
            User loginUser = userService.findByName(inputToken.getUsername());
            if(loginUser == null){
                //return null会自动抛出未知用户名异常
                return null;
            }
            //密码认证
            return new SimpleAuthenticationInfo(loginUser,loginUser.getPassword(),"");
        }else if(authenticationToken instanceof AdminUserToken){
            UsernamePasswordToken inputToken = (UsernamePasswordToken)authenticationToken;
            Admin loginAdmin = adminService.queryAdminByName(inputToken.getUsername());
            if(loginAdmin == null){
                return null;
            }
            return new SimpleAuthenticationInfo(loginAdmin,loginAdmin.getPassword(),"");
        }else{
            //既不是admin 又不是user
            return null;
        }
    }

}
